package com.wu.example;

import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class LocalBrowser extends BaseActivity {

	private static final String TAG = "LocalBrowser";
	private final Handler handler = new Handler();
	private WebView web_view;
	private Button button;
	private TextView text_view;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		autoFindViewsById();
		// rest on onCreate follews
		// turn on javaScript in the embedded browser
		web_view.getSettings().setJavaScriptEnabled(true);
		// expose a java object to JavaScript in the browser
		web_view.addJavascriptInterface(new AndroidBridge(
				new IJavaScriptAndroidBridge() {

					@Override
					public void doSomeing(String arg) {
						text_view.setText(arg);
					}
				}), "android");
		// set up a function to be called when JavaScript
		web_view.setWebChromeClient(new WebChromeClient() {
			@Override
			public boolean onJsAlert(WebView view, String url, String message,
					JsResult result) {
				Log.d(TAG, "onJsAlert(" + view + "," + url + "," + message
						+ "," + result + ")");
				Toast.makeText(LocalBrowser.this, message, 3000).show();
				result.confirm();
				return true;
			}
		});
		// Load the web page from a local asset
		web_view.loadUrl("file:///android_asset/index.html");
		// This function will be called when the user presses the
		// button on the android side
		button.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View view) {
				Log.d(TAG, "button.onClick(" + view + ")");
				web_view
						.loadUrl("javascript:callJsFromAndroid('Hello from Android')");
			}
		});
	}

	// private class AndroidBridge {
	//
	// public void callAndroid(final String arg) {// must be final
	// handler.post(new Runnable() {
	//
	// @Override
	// public void run() {
	// Log.d(TAG, "callAndroid(" + arg + ")");
	// text_view.setText(arg);
	// }
	// });
	// }
	// }
}
